var express = require('express');
var router = express.Router();
const Tag = require('../models/Tag');
const SchemaDef = require('../models/SchemaDef');
const Category = require('../models/Category');
var tools = require('../utils/tools')

/**
 * @swagger
 *
 * /cmdb/tags:
 *   get:
 *     tags:
 *       - 标签管理
 *     summary: 查询标签
 *     description: 查询标签
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.get('/', function (req, res, next) {
  Tag.find()
    .populate({ path: 'schemadef', select: 'code name' })
    .exec((err, docs) => {
      if (err) return tools.handleError(res, err);
      return res.json({ status: 'success', data: docs })
    })
});

/**
 * @swagger
 *
 * /cmdb/tags:
 *   post:
 *     tags:
 *       - 标签管理
 *     summary: 创建标签
 *     description: 同一模型下的标签编码不能重复。标签包含属性使用addattrs API管理
 *     parameters:
 *       - name: code
 *         description: 标签编码
 *         in: formData
 *         required: true
 *         type: string
 *       - name: name
 *         description: 标签名称
 *         in: formData
 *         required: true
 *         type: string
 *       - name: schemadef
 *         description: 模型ID
 *         in: formData
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.post('/', async function (req, res, next) {
  var { schemadef, code, name } = req.body
  var count = await Tag.count({ code, schemadef })
  if (count > 0) {
    return tools.handleError(res, "重复定义");
  } else {
    Tag.create({ code, name, schemadef }, function (err, doc) {
      if (err) return tools.handleError(res, err);
      return res.json({ status: 'success', data: doc })
    });
  }
});

/**
 * @swagger
 *
 * /cmdb/tags/{id}:
 *   get:
 *     tags:
 *       - 标签管理
 *     summary: 标签详情
 *     description:  标签详情
 *     parameters:
 *       - name: id
 *         description: 标签ID
 *         in: path
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.get('/:id', function (req, res, next) {
  Tag.findById(req.params.id)
    .populate({ path: 'schemadef', select: 'code name' })
    .exec((err, doc) => {
      if (err) return res.json({ status: 'failure' });
      return res.json({ status: 'success', data: doc })
    })
});

/**
 * @swagger
 *
 * /cmdb/tags/{id}:
 *   put:
 *     tags:
 *       - 标签管理
 *     summary: 更新标签
 *     description:  只能更新code, name
 *     parameters:
 *       - name: id
 *         description: 标签ID
 *         in: path
 *         required: true
 *         type: string
 *       - name: code
 *         description: 标签编码
 *         in: formData
 *         required: true
 *         type: string
 *       - name: name
 *         description: 标签名称
 *         in: formData
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.put('/:id', async function (req, res, next) {

  if (!tools.isValidObjectId(req.params.id)) {
    return tools.handleError(res, "ID不合法");
  }
  var { code, name } = req.body
  var beforeUpdate = await Tag.findById(req.params.id)
  if (!beforeUpdate) {
    return tools.handleError(res, "标签不存在");
  }
  var count = await Tag.count({ code, schemadef: beforeUpdate.schemadef, _id: { $ne: req.params.id } })
  if (count > 0) {
    return tools.handleError(res, "重复定义");
  }

  Tag.findByIdAndUpdate(req.params.id, { $set: { code, name } }, { new: true }, function (err, doc) {
    if (err) return tools.handleError(res, err);
    return res.json({ status: 'success', data: doc })
  });
});

/**
 * @swagger
 *
 * /cmdb/tags/{id}:
 *   delete:
 *     tags:
 *       - 标签管理
 *     summary: 删除标签
 *     description:  删除标签
 *     parameters:
 *       - name: id
 *         description: 标签ID
 *         in: path
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.delete('/:id', function (req, res, next) {
  Tag.findByIdAndDelete(req.params.id, function (err, doc) {
    if (err) return tools.handleError(res, err);
    return res.json({ status: 'success' })
  });
});

/**
 * @swagger
 *
 * /cmdb/tags/{id}/addattrs:
 *   put:
 *     tags:
 *       - 标签管理
 *     summary: 更新标签属性
 *     description:  单个属性，或属性数组，或逗号分隔。全量更新
 *     parameters:
 *       - name: id
 *         description: 标签ID
 *         in: path
 *         required: true
 *         type: string
 *       - name: attrs
 *         description: 属性
 *         in: formData
 *         required: true
 *         type: string
 *     responses:
 *       200:
 *         description: status/data结构
 */
router.put('/:id/addattrs', async function (req, res, next) {
  if (!tools.isValidObjectId(req.params.id)) {
    return tools.handleError(res, "ID不合法");
  }
  var beforeUpdate = await Tag.findById(req.params.id)
  if (!beforeUpdate) {
    return tools.handleError(res, "标签不存在");
  }

  var { attrs } = req.body
  attrs = attrs ? (tools.isArray(attrs) ? attrs : attrs.split(',')) : []

  if (attrs.length === 0) {
    return tools.handleError(res, "不合法的属性");
  }

  var schemaDef = await SchemaDef.findById(beforeUpdate.schemadef)
  var category = await Category.findOne({ code: schemaDef.category })

  var allAttrs = [...schemaDef.attrs, ...category.attrs]

  var attrs = attrs.filter(a => allAttrs.some(it => it.field === a))
  if (attrs.length === 0) {
    return tools.handleError(res, "模型或分类没有有效的属性定义");
  }

  beforeUpdate.attrs = attrs
  afterUpdate = await beforeUpdate.save();

  return res.json({ status: 'success', data: afterUpdate })
});

module.exports = router;
